'use strict';
const Subscription = require('egg').Subscription;
const moment = require('moment');
let count = 0;
let have = '无货';
const mess_time = moment();
class StockTask extends Subscription {
  // 通过 schedule 属性来设置定时任务的执行间隔等配置
  static get schedule() {
    return {
      interval: '30s', // 1 分钟间隔
      type: 'worker', // 一个worker执行
    };
  }

  // subscribe 是真正定时任务执行时被运行的函数
  async subscribe() {
    const { ctx } = this;
    try {
      const res1 = await ctx.service.goods.searchGoodInStock('MIC2421');
      if (res1.inStock === true) {
        await ctx.service.loginKey.sendEmail('3971有货了', '酷睿 i5/8GB/256GB/灰钴蓝');
        have = '酷睿 i5/8GB/256GB/灰钴蓝 有货';
      } else {
        console.log('1无货');
      }
      const res2 = await ctx.service.goods.searchGoodInStock('MIC2422');
      if (res2.inStock === true) {
        await ctx.service.loginKey.sendEmail('3971有货了', '酷睿 i5/8GB/256GB/石墨金');
        have = '酷睿 i5/8GB/256GB/石墨金 有货';
      } else {
        console.log('2无货');
      }
      const res3 = await ctx.service.goods.searchGoodInStock('MIC2423');
      if (res3.inStock === true) {
        await ctx.service.loginKey.sendEmail('3971有货了', '酷睿 i5/8GB/256GB/深酒红');
        have = '酷睿 i5/8GB/256GB/深酒红 有货';
      } else {
        console.log('3无货');
      }
      if (count % 100 === 0) {
        const result = await ctx.app.mysql.insert('day_mess', {
          message: `一天下来的统计:爬取次数:-${count}-次;状态:-${have}-`,
          created_time: moment().format('YYYY-MM-DD HH:mm:ss'),
        });
        console.log(result, '-----');
      }
      count++;
      have = '无货';
    } catch (err) {
      await ctx.app.mysql.insert('error_report', {
        error_msg: err,
        created_time: moment().format('YYYY-MM-DD HH:mm:ss'),
        module_place: '库存计划模块',
      });
    }
  }
}

module.exports = StockTask;
